//
//  WCG_M_DailyClickController.m
//  Project_B
//
//  Created by 甘霞 on 15/11/26.
//  Copyright © 2015年 Atom_Wang. All rights reserved.
//

#import "WCG_M_DailyClickController.h"
#import "GXSuggestModel.h"

@interface WCG_M_DailyClickController () <UIWebViewDelegate, UMSocialUIDelegate, UIScrollViewDelegate>
@property (nonatomic, assign) BOOL like;
@property (nonatomic, strong) NSMutableArray *likeArr;
@property (nonatomic, strong) NSMutableArray *unlikeArr;

@end

@implementation WCG_M_DailyClickController

- (void)dealloc
{
    self.webView.delegate = nil;
    self.webView.scrollView.delegate = nil;
    
}

#pragma mark - 视图将要出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //  隐藏导航栏
    [self.navigationController.navigationBar setHidden:YES];
    //  隐藏 tabBar
    NSArray *temp = self.tabBarController.view.subviews;
    UIView *view = temp[2];
    [UIView animateWithDuration:1.0f animations:^{
        view.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
    }];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SuggestModel" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@", self.titleStr];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"空");
    }
    if (fetchedObjects.count != 0) {
        for (SuggestModel *spe in fetchedObjects) {
            if (![spe.title isEqualToString:self.titleStr]) {
                self.like = NO;
            }else{
                self.like = YES;
            }
        }
    }
    if (!self.like) {
        [self createButtomLikeButton];
    }else
    {
        [self createButtomUnLikeButton];
    }
    
    [self.backBtn addTarget:self action:@selector(backTofront) forControlEvents:UIControlEventTouchUpInside];
    [self.repostBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    //    self.flashImage.userInteractionEnabled = YES;
    //    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    //    [self.flashImage addGestureRecognizer:tap];
    [self.likeBtn addTarget:self action:@selector(likeAction) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 视图将要消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //  隐藏 tabBar
    NSArray *temp = self.tabBarController.view.subviews;
    UIView *view = temp[2];
    [UIView animateWithDuration:1.0f animations:^{
        view.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49);
    }];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    self.navigationItem.title = @"";
    self.navigationController.navigationBar.hidden = YES;
    
    [self createWebViewWithFrame:self.view.bounds URL:[NSURL URLWithString:self.suggestModel.item_url]];
    self.webView.delegate = self;
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.delegate = self;
    [self loadNightMBProgress];
}

#pragma mark - 收藏按钮
- (void)likeAction
{
    if (self.like) {
        [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"bottom_btn_like_active"] forState:UIControlStateNormal];
        [self getDisLikeImage];
        self.flashImage.animationDuration = 0.5;
        self.flashImage.animationImages = self.unlikeArr;
        self.flashImage.animationRepeatCount = 1;
        [self.flashImage startAnimating];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"SuggestModel" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@", self.titleStr];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            NSLog(@"空~");
        }
        for (SuggestModel *sug in fetchedObjects) {
            [self.manager.managedObjectContext deleteObject:sug];
        }
        [self.manager saveContext];
    }else{
        [self getLikeImage];
        self.flashImage.animationDuration = 0.5;
        self.flashImage.animationRepeatCount = 1;
        self.flashImage.animationImages = self.likeArr;
        [self.flashImage startAnimating];
        [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"bottom_btn_liked"] forState:UIControlStateNormal];
        SuggestModel *suggest = [NSEntityDescription insertNewObjectForEntityForName:@"SuggestModel" inManagedObjectContext:self.manager.managedObjectContext];
        suggest.title = self.suggestModel.title;
        suggest.has_video = self.suggestModel.music[@"music_duration"];
        suggest.type = suggest.type;
        suggest.type_name = self.suggestModel.content[@"desc"];
        suggest.share_text = self.suggestModel.cp[@"avatar"];
        suggest.intro = self.suggestModel.cp[@"screen_name"];
        suggest.comment_count = self.suggestModel.gallery[@"image_count"];
        suggest.is_recommended = [NSNumber numberWithBool:self.suggestModel.is_recommended];
        suggest.share_image = self.suggestModel.thumb[@"raw"];
        suggest.content = [self.suggestModel.content[@"signature"] dataUsingEncoding:NSUTF8StringEncoding];
        suggest.cp = [self.suggestModel.type_name dataUsingEncoding:NSUTF8StringEncoding];
        suggest.item_url = self.suggestModel.item_url;
        suggest.today = @0;
        [self.manager saveContext];
    }
    self.like = !self.like;
}

- (void)getDisLikeImage
{
    self.unlikeArr = [NSMutableArray array];
    for (NSInteger i = 1; i <= 8; i++) {
        NSString *name = [NSString stringWithFormat:@"dislike_%ld@2x", i];
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        [self.unlikeArr addObject:img];
    }
}

- (void)getLikeImage
{
    self.likeArr = [NSMutableArray array];
    for (NSInteger i = 1; i <= 14; i++) {
        NSString *name = [NSString stringWithFormat:@"liked_%02ld@2x", i];
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        [self.likeArr addObject:img];
    }
}

#pragma mark - 分享
- (void)shareAction
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"563c60e267e58e6ae1000680"
                                      shareText:self.titleStr
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,nil]
                                       delegate:self];
}

#pragma mark - 返回按钮
- (void)backTofront
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}



- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"开始加载");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self removeHud];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"%@", error);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat y;
    if (scrollView.contentOffset.y > y) {
        [UIView animateWithDuration:1 animations:^{
            self.backBtn.alpha = 0;
            self.repostBtn.alpha = 0;
            self.likeBtn.alpha = 0;
        }];
        y = scrollView.contentOffset.y;
    }
    if (scrollView.contentOffset.y < y) {
        [UIView animateWithDuration:1 animations:^{
            self.backBtn.alpha = 0.8;
            self.repostBtn.alpha = 0.8;
            self.likeBtn.alpha = 0.8;
        }];
        y = scrollView.contentOffset.y;
    }
}

@end
